const fs = require('fs')
const path = require('path')

class UploadController {
  // 图片上传
  static async uploadImage(ctx, next) {
    // 获取key为image的图片
    const filesObj = ctx.request.files || {}
    let { image } = filesObj  // key = image

    if (!image) {
      ctx.err({ message: "no image param" })
      return
    }

    // 校验图片格式
    const fileTypes = ['image/jpeg', 'image/png']
    if (!fileTypes.includes(image.mimetype)) {
      ctx.err({ message: "the image format is not 'jpg', 'jpeg', 'png'" })
      return
    }

    const file = image

    // 读取上传的文件（文件会被koa-body上传至一个临时文件中）
    const reader = fs.createReadStream(file.filepath);

    // 获取图片上传后的目录路径
    const srcPath = __dirname.slice(0, __dirname.lastIndexOf("\\"))
    // 获取图片后缀
    const suffix = file.originalFilename.substring(file.originalFilename.lastIndexOf('.'), file.originalFilename.length)
    const writePath = path.join(srcPath, '/public/images/', file.newFilename + suffix)

    // 保存图片
    const writeStream = fs.createWriteStream(writePath)
    reader.pipe(writeStream)

    // 图片的http链接
    const httpPath = ctx.origin + '/images/' + file.newFilename + suffix

    ctx.succ({
      data: {
        path: httpPath
      }
    })
  }
}

module.exports = {
  UploadController
}